package com.weipai.springboot.module.service.impl;

import com.github.pagehelper.util.StringUtil;
import com.weipai.springboot.enums.DemandStatus;
import com.weipai.springboot.enums.OrderStatus;
import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.*;
import com.weipai.springboot.model.api.OrderRequest;
import com.weipai.springboot.model.api.PageResult;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.module.dao.GoodsDao;
import com.weipai.springboot.module.dao.InventoryDao;
import com.weipai.springboot.module.dao.OrderDao;
import com.weipai.springboot.module.dao.ShopCartDao;
import com.weipai.springboot.module.mapper.*;
import com.weipai.springboot.module.dao.*;
import com.weipai.springboot.module.mapper.ExchangeMapper;
import com.weipai.springboot.module.mapper.FreightMapper;
import com.weipai.springboot.module.mapper.OrderMapper;
import com.weipai.springboot.module.mapper.SaleReturnMapper;
import com.weipai.springboot.module.service.CustomerService;
import com.weipai.springboot.module.service.GoodsService;
import com.weipai.springboot.module.service.OrderService;
import com.weipai.springboot.module.service.SystemService;
import com.weipai.springboot.module.util.DateUtils;
import com.weipai.springboot.module.util.SessionUserUtil;
import com.weipai.springboot.util.PropUtils;
import com.weipai.springboot.util.PushUtil;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author songmengqiang
 * @create 2018-08-27 10:09
 **/
@Service
public class OrderServiceImpl implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private EmployeeIncomeMapper employeeIncomeMapper;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private ShopCartDao shopCartDao;
    @Autowired
    SessionUserUtil sessionUserUtil;
    @Autowired
    SaleReturnMapper saleReturnMapper;
    @Autowired
    ExchangeMapper exchangeMapper;
    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    OrderSublistMapper orderSublistMapper;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private SystemDao systemDao;
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private InventoryDetailDao inventoryDetailDao;
    @Autowired
    private ReputationHistoryDao reputationHistoryDao;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    private DemandDao demandDao;
    @Autowired
    private CustomerGiftMapper customerGiftMapper;
    @Autowired
    private SpecialGoodsDao specialGoodsDao;
    @Autowired
    private CenterDao centerDao;
    @Autowired
    IntegralGoodsDao integralGoodsDao;
    @Autowired
    private CustomerService customerService;

    @Override
    public Response getOrderList(String shopId,
                                 String customerId,
                                 Integer status,
                                 String orderNumber,
                                 String startTime,
                                 String endTime,
                                 String hasSubList,
                                 Integer page,
                                 Integer size,
                                 String keyword,
                                 Integer modeOfPayment,
                                 String draw) {
        Response response = new Response();
        Integer totalNum = orderDao.countOrderList(shopId, customerId, status, orderNumber, startTime, endTime);
        List<Map<String, Object>> list = orderDao.getOrderList(shopId, customerId, status, orderNumber, startTime, endTime, (page - 1) * size, size, keyword, modeOfPayment);
        Map<String, Object> mp = new HashMap<>();
        if (customerId != null && !"".equals(customerId)) {
            List<Map<String, Object>> orderByMoney = orderDao.getOrderByMoney(customerId);
            for (int i = 0; i < list.size(); i++) {
                String orderNumber1 = (String) list.get(i).get("orderNumber");
//            System.out.print(orderNumber1);
                for (int j = 0; j < orderByMoney.size(); j++) {
                    if (orderNumber1.equals(orderByMoney.get(j).get("order_number"))) {
                        mp.put("saleReturnPrice", orderByMoney.get(j).get("saleReturnPrice"));
                        list.get(i).put("saleReturnPrice", orderByMoney.get(j).get("saleReturnPrice"));
                    }
                }
            }
        } else {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).put("saleReturnPrice", "");
            }
        }


        if ("Y".equals(hasSubList)) {
            for (Map<String, Object> order : list) {
                String orderNumberTmp = order.get("orderNumber").toString();
                List<Map<String, Object>> subList = orderDao.getOrderSublist(orderNumberTmp);
                order.put("subList", subList);
            }
        }
        if ("N".equals(hasSubList)) {
            if (null != orderDao.getAllRealPay(startTime, endTime)) {
                response.put("realPay", orderDao.getAllRealPay(startTime, endTime));
            } else {
                response.put("realPay", 0);
            }
        }

        if (keyword != "" && keyword != null) {
            totalNum = list.size();
        }

        PageResult<Map<String, Object>> pageList = new PageResult<>(list, page, size, totalNum, draw);
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    //更改 订单状态
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    @Override
    public Response update(Order order) {
        Response response = new Response();
        if (order.getOrderStatus() != null) {
            if (order.getOrderStatus() == OrderStatus.SUCCESS.getStatus()) {
                profitSharing(order.getOrderNumber());
            }
        }
        int r = orderDao.update(order);
        if (r == 1) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    /**
     * 员工的收益
     * 店铺的未结算
     *
     * @param orderNumber
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void profitSharing(String orderNumber) {
        Map<String, Object> order = orderDao.getOrderInfoByOrderNumber(orderNumber);
        Integer modeOfPayment = (Integer) order.get("mode_of_payment");
        if (null != order) {
            if (modeOfPayment != null && modeOfPayment != 6) {
                String customerId = order.get("customerId").toString();
                //下订单用户
                Customer customer = customerDao.getCustomerById(customerId);
                String adminCode = customer.getAdminCode();
                if (!Strings.isEmpty(adminCode)) {
                    Admin admin = adminDao.getAdminByAdminCode(adminCode);
                    if (null != admin) {
                        //获得收益的员工
                        Customer customer1 = customerDao.getCustomerById(admin.getCustomerId());
                        if (null != customer1) {
                            Map<String, Object> map = systemDao.getCommissionRateByType(0);
                            int newPrice = Integer.parseInt(order.get("realPay").toString());
                            BigDecimal a = new BigDecimal(Integer.parseInt(map.get("commissionRate").toString())).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN);
                            BigDecimal c = new BigDecimal(newPrice).multiply(a);
                            int f = c.intValue();
                            customer1.setCashMoney(customer1.getCashMoney() + f);
                            customerDao.updateByPrimaryKey(customer1);
                            //员工提成记录
                            saveEmployeeIncome(customer1.getCustomerId(), orderNumber, f, 1, customerId);
                        }
                    }
                }

                //商品未结算统计
                List<Map<String, Object>> orderSublist = orderDao.getSublist(orderNumber);
                int size01 = orderSublist.size();
                String shopId = orderSublist.get(0).get("shopId").toString();
                int allProfit = 0;
                for (int i = 0; i < size01; i++) {
                    Map<String, Object> map = orderSublist.get(i);
                    int goodsNumber = Integer.parseInt(map.get("goodsNumber").toString());
                    int costPrice = Integer.parseInt(map.get("costPrice").toString());
                    int profit = costPrice * goodsNumber;
                    allProfit += profit;
                }
                //更新商品未结算的金额
                shopDao.updateNoWithdrawal(shopId, allProfit);
            }
        }
    }

    @Override
    public Response getOrderDetail(String orderNumber) {
        Response response = new Response();

        Order order = orderDao.getOrderInfoByOrderNumber22(orderNumber);
        CustomerInvoice invoice = null;
        List<Map<String, Object>> sublist = orderDao.getOrderSublist(orderNumber);
        response.setCode(RetCode.SUCCESS);
        if (0 == order.getIsInvoice()) {
            response.put("individual", "0");
        } else {
            if (order.getInvoiceId() != null) {
                invoice = centerDao.getInvoiceById(order.getInvoiceId());
                response.put("invoice", invoice);
            } else {
                response.put("individual", "3");
            }
        }
        response.put("subList", sublist);
        return response;
    }

    @Override
    public Response deleteOrder(String orderNumber) {
        Response response = new Response();
        //判断如果此订单用了优惠券，待付款状态，删除订单，优惠券 恢复到之前
        Order order = orderMapper.getOrderInfoByOrderNumber22(orderNumber);
        if (order != null) {
            if (order.getIsUseGift() == 1) {
                if (order.getCustomerGiftId() != null && order.getCustomerGiftId() != "") {
                    CustomerGift customerGift = customerGiftMapper.selectByPrimaryKey(Integer.parseInt(order.getCustomerGiftId()));
                    if (customerGift != null) {
                        customerGift.setIsUse(0);
                        customerGiftMapper.updateByPrimaryKeySelective(customerGift);
                    }
                }
            }
        }
        orderDao.deleteOrder(orderNumber);
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    @Override
    public Response getOrderCountList(String time) {
        Response response = new Response();
        List<Map<String, Object>> list = orderDao.getOrderCountList(time);
        response.setCode(RetCode.SUCCESS);
        response.put("list", list);
        return response;
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    @Override
    public Response save(OrderRequest request) {
        Response response = new Response();
        Order order = new Order();
        if (Strings.isEmpty(request.getStorageId())) {
            response.setCode(RetCode.REQUEST_ERROR);
            return response;
        } else {
            if (!"".equals(request.getSpecialOfferId()) && request.getSpecialOfferId() != null) {
                String goodsId = request.getGoodsList().get(0).getGoodsId();
                SpecialGoods specialGoods = specialGoodsDao.selectByGoodsIdAndspecialId(goodsId, request.getSpecialOfferId());
                if (specialGoods.getSoldOutGoods() < specialGoods.getGoodsNum()) {
                    specialGoods.setSoldOutGoods(specialGoods.getSoldOutGoods() + 1);
                    specialGoodsDao.updateSpecialGoods(specialGoods);
                } else {
                    response.setCode(RetCode.GOODS_EMPTY);
                    return response;
                }
            }


            order.setOrderStatus(1);  //订单状态
            if (StringUtil.isNotEmpty(request.getFhrq())) {
                order.setFhrq(request.getFhrq());
            }
            if (request.getType().equals("3")) { //积分兑换
                order.setModeOfPayment(6); //积分支付
                order.setOrderStatus(2);
                order.setCustomerGiftId(request.getCustomerGiftId()); //积分商品 用于保存  integralGoodsId
                order.setPayTime(DateUtils.timeFormat(System.currentTimeMillis()));
                IntegralGoods integralGoods = integralGoodsDao.getIntegralGoodsById(request.getCustomerGiftId());
                if (integralGoods.getSoldOutNumber() < integralGoods.getIntegralGoodsNumber()) {
                    integralGoods.setSoldOutNumber(integralGoods.getSoldOutNumber() + 1);
                    if (1 == integralGoodsDao.updateByPrimaryKey(integralGoods)) {

                    } else {
                        response.setCode(RetCode.GOODS_INTERGRALFAIL);
                        return response;
                    }
                } else {
                    response.setCode(RetCode.GOODS_INTERGRAL);
                    return response;
                }
            }
            order.setOrderId(UUID.randomUUID().toString()); //订单编号
            order.setOrderNumber(outTradeNo());
            order.setCustomerId(request.getCustomerId());
            if (request.getAmountPayable() != null) {
                order.setAmountPayable(request.getAmountPayable()); //应付金额
            } else {
                response.setCode(RetCode.AMOUNT_PAYABLE);
                return response;
            }
            order.setIsUseGift(request.getIsUseGift()); //是否使用优惠券，默认为0,1使用优惠券
            order.setCustomerGiftId(request.getCustomerGiftId()); //我的优惠券的id
            order.setDiscountsMoney(request.getDiscountsMoney()); //优惠金额
            if (request.getRealPay() != null) {
                order.setRealPay(request.getRealPay()); //实付金额
            } else {
                response.setCode(RetCode.REAL_PAY);
                return response;
            }
            if (request.getAddressId() != null) {
                order.setAddressId(request.getAddressId()); //收货地址id
            } else {
                response.setCode(RetCode.ADDRESS_ID);
                return response;
            }
            order.setFreightMoney(request.getFreightMoney()); //运费
            if (request.getShopId() != null) {
                order.setShopId(request.getShopId()); //商铺id
            } else {
                response.setCode(RetCode.SHOP_ID);
                return response;
            }
            if (!"".equals(request.getIsInvoice()) && request.getIsInvoice() != null) {
                order.setIsInvoice(request.getIsInvoice()); //是否开发票  0不开发票，1开发票[
                if (request.getIsInvoice() == 1) {
                    if (!"".equals(request.getInvoiceId()) && request.getInvoiceId() != null) {
                        order.setInvoiceId(request.getInvoiceId());//发票的id
                        if (!"".equals(request.getInvoiceName()) && request.getInvoiceName() != null) {
                            order.setInvoiceName(request.getInvoiceName()); //发票人姓名
                        }
                        if (!"".equals(request.getInvoiceMobile()) && request.getInvoiceMobile() != null) {
                            response.setCode(RetCode.INVOICE_SPECIFICAL);
                            return response;
                        }
                    } else if (!"".equals(request.getInvoiceMobile()) && request.getInvoiceMobile() != null) {
                        order.setInvoiceMobile(request.getInvoiceMobile()); //发票人手机号
                    } else {
                        response.setCode(RetCode.INVOICE_ISINVOICE);
                        return response;
                    }
                }
            }
            if (request.getStorageId() != null) {
                order.setStorageId(request.getStorageId()); //仓储id
            } else {
                response.setCode(RetCode.STORAGE_ID);
                return response;
            }
            order.setIsExchangeGoods(0);
            order.setIsSaleReturn(0);
            order.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis())); //创建时间
            order.setMessage(request.getMessage());//买家留言
            List<OrderSublist> subOrderList = new ArrayList<>();
            List<OrderRequest.OrderGoods> orderGood = request.getGoodsList();
            if (orderGood.isEmpty()) {
                response.setCode(RetCode.REQUEST_ERROR);
                return response;
            }
            for (OrderRequest.OrderGoods orderGoods : request.getGoodsList()) {
                OrderSublist orderSublist = new OrderSublist();
                orderSublist.setGoodsId(orderGoods.getGoodsId());
                orderSublist.setOrderNumber(order.getOrderNumber());
                orderSublist.setGoodsPrice(orderGoods.getGoodsPrice());
                orderSublist.setGoodsNumber(orderGoods.getGoodsNumber());
                orderSublist.setShopId(order.getShopId());
                orderSublist.setStorageId(order.getStorageId());
                orderSublist.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
                orderSublist.setCustomerId(request.getCustomerId());
                subOrderList.add(orderSublist);
                //type为2表示购物车结算--删除购物车商品
                if (request.getType().equals("2")) {
                    shopCartDao.deleteById(request.getCustomerId(), orderGoods.getGoodsId());
                }
            }
            orderDao.insertOrder(order);
            //查看订单是否使用优惠券
            if (order.getIsUseGift() == 1) {
                if (order.getCustomerGiftId() != null && order.getCustomerGiftId() != "") {
                    CustomerGift customerGift = customerGiftMapper.selectByPrimaryKey(Integer.parseInt(order.getCustomerGiftId()));
                    customerGift.setIsUse(1); //改变优惠券状态已使用
                    customerGiftMapper.updateByPrimaryKeySelective(customerGift);
                }
            }
            if (subOrderList != null && subOrderList.size() > 0) {
                orderDao.insertSubOrderList(subOrderList);
            }
            response.setCode(RetCode.SUCCESS);
            response.put("orderNumber", order.getOrderNumber());
            response.put("realPay", order.getRealPay());
        }
        return response;
    }


    /**
     * 生成订单号
     *
     * @return
     */
    public String outTradeNo() {
        Random random = new Random();
        return System.currentTimeMillis() + String.valueOf(random.nextInt(2000000000));
    }

    //退货申请
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response returnApplication(SaleReturn saleReturn, String imgUrl) {
        Response response = new Response();
        //验证唯一
        List<SaleReturn> saleReturnList = saleReturnMapper.verSole(saleReturn.getOrderNumber(), saleReturn.getGoodsId());
        //获得总订单
        Order order = orderDao.getOrderInfoByOrderNumber22(saleReturn.getOrderNumber());
        if (null != order) {
            Integer status = order.getOrderStatus();
            if (status == OrderStatus.SUCCESS.getStatus()) {           //如果是 已完成状态  单个商品退货
                if (saleReturnList.size() > 0) {    //验证是否已有退换货
                    response.setCode(RetCode.CASHRECORD_VER);
                    return response;
                } else {
                    if (null == saleReturn.getGoodsNumber()) {
                        response.setCode(RetCode.NO_GOODSNUMBER);
                        return response;
                    }
                    if (null == saleReturn.getGoodsPrice()) {
                        response.setCode(RetCode.NO_GOODSPRICE);
                        return response;
                    }
                    saleReturn.setSaleReturnNumber(UUID.randomUUID().toString());
                    saleReturn.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
                    saleReturn.setCustomerId(sessionUserUtil.getUserAttr().getCustomerId());
                    saleReturn.setReturnImg(imgUrl);
                    saleReturn.setSaleReturnStatus(0);
                    saleReturn.setIsAudit(0);
                    //通过 goodsId ,orderNumber 获得子订单
                    OrderSublist orderSublist = orderSublistMapper.getOrderSublistByGoodsIdAndOrderNumber(saleReturn.getOrderNumber(), saleReturn.getGoodsId());
                    //判断是否有过换货,就不能退货
                    if (orderSublist != null) {
                        if (orderSublist.getIsExchangeGoodsSublist() == 1) {
                            response.setCode(RetCode.CASHRECORD_VER);
                            return response;
                        } else {
                            //标记订单 是否已经退货
                            order.setIsSaleReturn(1);
                            orderSublist.setIsSaleReturnSublist(1);
                        }
                        orderDao.updateByPrimaryKeySelective(order);
                        orderSublistMapper.updateByPrimaryKeySelective(orderSublist);
                    }
                }
                if (null == saleReturn.getGoodsNumber()) {
                    response.setCode(RetCode.NO_GOODSNUMBER);
                    return response;
                }
                if (null == saleReturn.getGoodsPrice()) {
                    response.setCode(RetCode.NO_GOODSPRICE);
                    return response;
                }
                saleReturn.setSaleReturnNumber(UUID.randomUUID().toString());
                saleReturn.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
                saleReturn.setCustomerId(sessionUserUtil.getUserAttr().getCustomerId());
                saleReturn.setReturnImg(imgUrl);
                saleReturn.setSaleReturnStatus(0);
                saleReturn.setIsAudit(0);
                //通过 goodsId ,orderNumber 获得子订单
                OrderSublist orderSublist = orderSublistMapper.getOrderSublistByGoodsIdAndOrderNumber(saleReturn.getOrderNumber(), saleReturn.getGoodsId());
                //判断是否有过换货,就不能退货
                if (orderSublist != null) {
                    if (orderSublist.getIsExchangeGoodsSublist() == 1) {
                        response.setCode(RetCode.CASHRECORD_VER);
                        return response;
                    } else {
                        //标记订单 是否已经退货
                        order.setIsSaleReturn(1);
                        orderSublist.setIsSaleReturnSublist(1);
                    }
                    orderDao.updateByPrimaryKeySelective(order);
                    orderSublistMapper.updateByPrimaryKeySelective(orderSublist);
                }
                if (orderDao.saveSaleReturn(saleReturn) == 1) {
                    response.setCode(RetCode.SUCCESS);
                } else {
                    response.setCode(RetCode.REQUEST_ERROR);
                }
            } else if (status == OrderStatus.UNDELIVERED.getStatus() || status == OrderStatus.IN_GENERATE.getStatus()) {        //如果是 待发货状态  则全退
                if (saleReturnList.size() > 0) {    //验证是否已有退换货
                    response.setCode(RetCode.CASHRECORD_VER);
                    return response;
                } else {
                    //通过订单号获取  其下所有子订单 商品
                    List<Map<String, Object>> mapList = orderSublistMapper.getSublist(saleReturn.getOrderNumber());

                    Integer size = mapList.size();
                    boolean flag = true;

                    for (int j = 0; j < size; j++) {
                        int goodsPrice;
                        if (order.getIsUseGift() == 1 && order.getDiscountsMoney() != null && !"".equals(order.getDiscountsMoney())) {
                            if (flag) {
                                goodsPrice = Integer.parseInt(mapList.get(j).get("goodsPrice").toString());
                                if (goodsPrice > order.getDiscountsMoney()) {
                                    goodsPrice = goodsPrice - order.getDiscountsMoney();
                                    flag = false;
                                    SaleReturn saleReturn1 = new SaleReturn();
                                    if (order.getFreightMoney() > 0) {
                                        if (j == 0) {
                                            saleReturn1.setFreightMoney(order.getFreightMoney());
                                        }
                                    }
                                    saleReturn1.setSaleReturnNumber(UUID.randomUUID().toString());
                                    saleReturn1.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
                                    saleReturn1.setCustomerId(sessionUserUtil.getUserAttr().getCustomerId());
                                    saleReturn1.setSaleReturnStatus(0);
                                    saleReturn1.setIsAudit(0);
                                    saleReturn1.setOrderNumber(saleReturn.getOrderNumber());
                                    saleReturn1.setCustomCause(saleReturn.getCustomCause());
                                    saleReturn1.setSaleReturnCause(saleReturn.getSaleReturnCause());
                                    saleReturn1.setStorageId(saleReturn.getStorageId());
                                    saleReturn1.setReturnImg(imgUrl);
                                    saleReturn1.setExpressCompany(saleReturn.getExpressCompany());
                                    saleReturn1.setGoodsNumber(Integer.parseInt(mapList.get(j).get("goodsNumber").toString()));
                                    saleReturn1.setGoodsId(mapList.get(j).get("goodsId").toString());
                                    saleReturn1.setGoodsPrice(goodsPrice);

                                    saleReturn1.setShopId(mapList.get(j).get("shopId").toString());
                                    //通过 goodsId ,orderNumber 获得子订单
                                    OrderSublist orderSublist = orderSublistMapper.getOrderSublistByGoodsIdAndOrderNumber(saleReturn.getOrderNumber(), mapList.get(j).get("goodsId").toString());
                                    if (orderSublist != null) {
                                        orderSublist.setIsSaleReturnSublist(1);
                                        orderSublistMapper.updateByPrimaryKeySelective(orderSublist);
                                        orderDao.saveSaleReturn(saleReturn1); //形成一条退货记录
                                    }
                                }
                            } else {
                                SaleReturn saleReturn1 = new SaleReturn();
                                if (order.getFreightMoney() > 0) {
                                    if (j == 0) {
                                        saleReturn1.setFreightMoney(order.getFreightMoney());
                                    }
                                }
                                saleReturn1.setSaleReturnNumber(UUID.randomUUID().toString());
                                saleReturn1.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
                                saleReturn1.setCustomerId(sessionUserUtil.getUserAttr().getCustomerId());
                                saleReturn1.setSaleReturnStatus(0);
                                saleReturn1.setIsAudit(0);
                                saleReturn1.setOrderNumber(saleReturn.getOrderNumber());
                                saleReturn1.setCustomCause(saleReturn.getCustomCause());
                                saleReturn1.setSaleReturnCause(saleReturn.getSaleReturnCause());
                                saleReturn1.setStorageId(saleReturn.getStorageId());
                                saleReturn1.setReturnImg(imgUrl);
                                saleReturn1.setExpressCompany(saleReturn.getExpressCompany());
                                saleReturn1.setGoodsNumber(Integer.parseInt(mapList.get(j).get("goodsNumber").toString()));
                                saleReturn1.setGoodsId(mapList.get(j).get("goodsId").toString());
                                saleReturn1.setGoodsPrice(Integer.parseInt(mapList.get(j).get("goodsPrice").toString()));

                                saleReturn1.setShopId(mapList.get(j).get("shopId").toString());
                                //通过 goodsId ,orderNumber 获得子订单
                                OrderSublist orderSublist = orderSublistMapper.getOrderSublistByGoodsIdAndOrderNumber(saleReturn.getOrderNumber(), mapList.get(j).get("goodsId").toString());
                                if (orderSublist != null) {
                                    orderSublist.setIsSaleReturnSublist(1);
                                    orderSublistMapper.updateByPrimaryKeySelective(orderSublist);
                                    orderDao.saveSaleReturn(saleReturn1); //形成一条退货记录
                                }
                            }
                        } else {
                            SaleReturn saleReturn1 = new SaleReturn();
                            if (order.getFreightMoney() > 0) {
                                if (j == 0) {
                                    saleReturn1.setFreightMoney(order.getFreightMoney());
                                }
                            }
                            saleReturn1.setSaleReturnNumber(UUID.randomUUID().toString());
                            saleReturn1.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
                            saleReturn1.setCustomerId(sessionUserUtil.getUserAttr().getCustomerId());
                            saleReturn1.setSaleReturnStatus(0);
                            saleReturn1.setIsAudit(0);
                            saleReturn1.setOrderNumber(saleReturn.getOrderNumber());
                            saleReturn1.setCustomCause(saleReturn.getCustomCause());
                            saleReturn1.setSaleReturnCause(saleReturn.getSaleReturnCause());
                            saleReturn1.setStorageId(saleReturn.getStorageId());
                            saleReturn1.setReturnImg(imgUrl);
                            saleReturn1.setExpressCompany(saleReturn.getExpressCompany());
                            saleReturn1.setGoodsNumber(Integer.parseInt(mapList.get(j).get("goodsNumber").toString()));
                            saleReturn1.setGoodsId(mapList.get(j).get("goodsId").toString());
                            saleReturn1.setGoodsPrice(Integer.parseInt(mapList.get(j).get("goodsPrice").toString()));

                            saleReturn1.setShopId(mapList.get(j).get("shopId").toString());
                            //通过 goodsId ,orderNumber 获得子订单
                            OrderSublist orderSublist = orderSublistMapper.getOrderSublistByGoodsIdAndOrderNumber(saleReturn.getOrderNumber(), mapList.get(j).get("goodsId").toString());
                            if (orderSublist != null) {
                                orderSublist.setIsSaleReturnSublist(1);
                                orderSublistMapper.updateByPrimaryKeySelective(orderSublist);
                                orderDao.saveSaleReturn(saleReturn1); //形成一条退货记录
                            }
                        }


                    }
                    order.setIsSaleReturn(1);
                    orderDao.updateByPrimaryKeySelective(order);
                    response.setCode(RetCode.SUCCESS);

                }
            } else {
                response.setCode(RetCode.NONSUPPORT);
            }
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }


    //换货申请
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response exchangeApplication(Exchange exchange) {
        Response response = new Response();
        //验证唯一
        List<Exchange> exchangeList = exchangeMapper.verSole(exchange.getOrderNumber(), exchange.getGoodsId());

        if (exchangeList.size() > 0) {
            response.setCode(RetCode.CASHRECORD_VER);
            return response;
        } else {
            String customerId = sessionUserUtil.getUserAttr().getCustomerId();
            exchange.setCustomerId(customerId);
            exchange.setExchangeStatus(0);
            exchange.setIsAudit(0);
            //标记订单 是否已经换货
            Order order1 = orderDao.getOrderInfoByOrderNumber22(exchange.getOrderNumber());
            //通过 goodsId ,orderNumber 获得子订单
            OrderSublist orderSublist = orderSublistMapper.getOrderSublistByGoodsIdAndOrderNumber(exchange.getOrderNumber(), exchange.getGoodsId());

            //判断是否有过退货,就不能换货
            if (orderSublist.getIsSaleReturnSublist() == 1) {
                response.setCode(RetCode.CASHRECORD_VER);
                return response;
            } else {
                order1.setIsExchangeGoods(1);
                orderSublist.setIsExchangeGoodsSublist(1);
            }
            orderDao.updateByPrimaryKeySelective(order1);
            orderSublistMapper.updateByPrimaryKeySelective(orderSublist);
            if (orderDao.saveExchange(exchange) == 1) {
                response.setCode(RetCode.SUCCESS);
            } else {
                response.setCode(RetCode.REQUEST_ERROR);
            }

        }
        return response;
    }

    //跳转换货详情页面
    @Override
    public Response exchangeGoodsInfo(String orderNumber, String goodsId) {
        Response response = new Response();
        List<Map<String, Object>> list = new ArrayList<>();
        Order order = orderMapper.getOrderInfoByOrderNumber22(orderNumber);
        //通过订单号获取  其下所有子订单 商品
        List<Map<String, Object>> mapList = orderSublistMapper.getSublist(orderNumber);
        if ((order.getOrderStatus() == OrderStatus.UNDELIVERED.getStatus() || order.getOrderStatus() == OrderStatus.IN_GENERATE.getStatus()) && mapList.size() > 1) {
            Integer size = mapList.size();
            for (int j = 0; j < size; j++) {
                //查询产品图片、商品名称、商品规格
                Map<String, Object> goodsMap = goodsDao.getGoodsInfoByGoodsId(mapList.get(j).get("goodsId").toString());
                if (goodsMap != null) {
                    //获取换货界面的商品信息、地址信息
                    Map<String, Object> addressMap = orderDao.getOrderInfoByOrderNumberAndGoodsId(orderNumber, mapList.get(j).get("goodsId").toString());
                    addressMap.put("productImg", goodsMap.get("productImg"));//产品图片
                    addressMap.put("goodsName", goodsMap.get("goodsName"));//商品名称
                    addressMap.put("goodsSpec", goodsMap.get("goodsSpec"));//商品规格
                    list.add(addressMap);
                } else {
                    response.setCode(RetCode.NO_DATA);//暂无数据
                }
            }
        } else {
            //查询产品图片、商品名称、商品规格
            Map<String, Object> goodsMap = goodsDao.getGoodsInfoByGoodsId(goodsId);

            if (goodsMap != null) {
                //获取换货界面的商品信息、地址信息
                Map<String, Object> addressMap = orderDao.getOrderInfoByOrderNumberAndGoodsId(orderNumber, goodsId);
                addressMap.put("productImg", goodsMap.get("productImg"));
                addressMap.put("goodsName", goodsMap.get("goodsName"));
                addressMap.put("goodsSpec", goodsMap.get("goodsSpec"));
                list.add(addressMap);
            } else {
                response.setCode(RetCode.NO_DATA);
            }
        }
        response.setCode(RetCode.SUCCESS);
        response.put("list", list);
        return response;
    }

    // 退换/售后列表 -  申请记录 -   查看详情
    @Override
    public Response geGoodsInfo(String orderNumber, String goodsId, String saleReturnId, String exchangeId) {
        Response response = new Response();
        //查询产品图片、商品名称、商品规格
        Map<String, Object> goodsMap = goodsDao.getGoodsInfoByGoodsId(goodsId);

        if (goodsMap != null) {
            //获取换货界面的商品信息、地址信息
            Map<String, Object> addressMap = orderDao.getOrderInfoByOrderNumberAndGoodsId(orderNumber, goodsId);
            addressMap.put("productImg", goodsMap.get("productImg"));
            addressMap.put("goodsName", goodsMap.get("goodsName"));
            addressMap.put("goodsSpec", goodsMap.get("goodsSpec"));

            //获取 退货详情
            if (saleReturnId != "" && saleReturnId != null) {
                SaleReturn saleReturn = saleReturnMapper.selectByPrimaryKey(saleReturnId);
                addressMap.put("saleReturnStatus", saleReturn.getSaleReturnStatus()); //申请状态
                addressMap.put("saleReturnCause", saleReturn.getSaleReturnCause());//申请原因
                addressMap.put("goodsPrice", saleReturn.getGoodsPrice());//退款金额
                addressMap.put("createTime", saleReturn.getCreateTime());//申请时间
                addressMap.put("saleReturnNumber", saleReturn.getSaleReturnNumber());//售后编号
                addressMap.put("isAudit", saleReturn.getIsAudit());//是否审核
                addressMap.put("expressNumber", saleReturn.getExpressNumber());//返回运单号
                addressMap.put("goodsNumber", saleReturn.getGoodsNumber());//返回退货数量
                addressMap.put("freightMoney", saleReturn.getFreightMoney());//退货运费
            }
            //获取 换货详情
            if (exchangeId != "" && exchangeId != null) {
                Exchange exchange = exchangeMapper.selectByPrimaryKey(exchangeId);
                addressMap.put("exchangeStatus", exchange.getExchangeStatus()); //申请状态
                addressMap.put("exchangeCause", exchange.getExchangeCause());//申请原因
                addressMap.put("createTime", exchange.getCreateTime());//申请时间
                addressMap.put("exchangeNumber", exchange.getExchangeNumber());//售后编号
                addressMap.put("isAudit", exchange.getIsAudit());//是否审核
                addressMap.put("expressNumber", exchange.getExpressNumber());//返回运单号
                addressMap.put("goodsNumber", exchange.getGoodsNumber());//返回换货数量
            }
            response.setCode(RetCode.SUCCESS);
            response.setData(addressMap);
        } else {
            response.setCode(RetCode.NO_DATA);
        }

        return response;
    }


    //退换/售后列表 - 申请记录 - 查看详情 - 填写 运单号 快递公司
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response inserExpressInfo(String expressNumber,
                                     String expressCompany,
                                     String saleReturnId,
                                     String exchangeId) {
        Response response = new Response();
        //获取 更新退换 运单号
        if (saleReturnId != "" && saleReturnId != null) {
            SaleReturn saleReturn = saleReturnMapper.selectByPrimaryKey(saleReturnId);
            saleReturn.setExpressNumber(expressNumber);
            saleReturn.setSaleReturnStatus(4);
            saleReturn.setExpressCompany(expressCompany);
            saleReturnMapper.updateByPrimaryKeySelective(saleReturn);
            response.setCode(RetCode.SUCCESS);
        }
        //获取 更新换货 运单号
        if (exchangeId != "" && exchangeId != null) {
            Exchange exchange = exchangeMapper.selectByPrimaryKey(exchangeId);
            exchange.setExpressNumber(expressNumber);
            exchange.setExpressCompany(expressCompany);
            exchange.setExchangeStatus(4);
            exchangeMapper.updateByPrimaryKeySelective(exchange);
            response.setCode(RetCode.SUCCESS);
        }
        return response;
    }

    //换货申请的审核
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response auditExchange(String exchangeNumber, Integer isAudit) {
        Response response = new Response();
        String auditUserId = sessionUserUtil.getAdminAttr().getAdminId();
        Exchange exchange = exchangeMapper.getExchangeByExchangeNumber(exchangeNumber);
        //通过 goodsId ,orderNumber 获得子订单
        OrderSublist orderSublist = orderSublistMapper.getOrderSublistByGoodsIdAndOrderNumber(exchange.getOrderNumber(), exchange.getGoodsId());
        if (orderDao.auditExchange(auditUserId, exchangeNumber, isAudit) == 1) {
            orderSublist.setIsExchangeGoodsSublist(isAudit);
            orderSublistMapper.updateByPrimaryKeySelective(orderSublist);
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //审核退货订单
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response auditReturnOrder(String saleReturnNumber, Integer isAudit) {
        Response response = new Response();
        String auditUserId = sessionUserUtil.getAdminAttr().getAdminId();
        SaleReturn saleReturn = saleReturnMapper.getSaleReturnBySaleReturnNumber(saleReturnNumber);

        //通过 goodsId ,orderNumber 获得子订单
        OrderSublist orderSublist = orderSublistMapper.getOrderSublistByGoodsIdAndOrderNumber(saleReturn.getOrderNumber(), saleReturn.getGoodsId());

        if (saleReturn != null && orderSublist != null) {
            //退货 单状态变成  2 表示财务待退款
            if (isAudit == 1) {
                Order order = orderDao.getOrderInfoByOrderNumber22(saleReturn.getOrderNumber());
                if (order.getOrderStatus() == OrderStatus.UNDELIVERED.getStatus() || order.getOrderStatus() == OrderStatus.IN_GENERATE.getStatus()) {
                    saleReturn.setIsAudit(1);
                    saleReturn.setSaleReturnStatus(2);
                    saleReturn.setAuditUserId(auditUserId);
                } else {
                    saleReturn.setIsAudit(1);
                    saleReturn.setSaleReturnStatus(1);
                    saleReturn.setAuditUserId(auditUserId);
                }
            } else if (isAudit == 2) {
                saleReturn.setSaleReturnStatus(2);
                saleReturn.setAuditUserId(auditUserId);
            } else {
                saleReturn.setIsAudit(-1);
                saleReturn.setAuditUserId(auditUserId);
                orderSublist.setIsSaleReturnSublist(-1);
            }
            saleReturnMapper.updateByPrimaryKeySelective(saleReturn);
            orderSublistMapper.updateByPrimaryKeySelective(orderSublist);
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }


    //退货订单的确认收货
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response receivingReturnOrder(String saleReturnNumber) {
        //此接口中应该操作：库存增加、用户退款
        Response response = new Response();
        String userId = sessionUserUtil.getAdminAttr().getCustomerId();
        if (orderDao.updateSaleReturnStatus(userId, saleReturnNumber, 2) == 1) {
            SaleReturn saleReturn = orderDao.getSaleReturnBySaleReturnNumber(saleReturnNumber);
            Map<String, Object> map = goodsDao.getSkuNumberByGoodsId(saleReturn.getGoodsId());

            //减掉商品的库存
            Map<String, Object> inventoryMap = inventoryDao.getStorageGoodsNum(saleReturn.getStorageId(), map.get("skuNumber").toString());
            if (null == inventoryMap) {
                Inventory inventory = new Inventory();
                inventory.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
                inventory.setGoodsNumber(saleReturn.getGoodsNumber());
                inventory.setShopId(saleReturn.getShopId());
                inventory.setSkuNumber(map.get("skuNumber").toString());
                inventory.setStorageId(saleReturn.getStorageId());
                inventoryDao.insert(inventory);
            } else {
                Inventory inventory = inventoryDao.selectByPrimaryKey((Long) (inventoryMap.get("inventoryId")));
                inventory.setGoodsNumber(inventory.getGoodsNumber() + saleReturn.getGoodsNumber());
                inventoryDao.updateByPrimaryKeySelective(inventory);
            }
            //记录商品入库明细
            InventoryIn in = new InventoryIn();
            in.setStorageId(saleReturn.getStorageId());
            in.setShopId(saleReturn.getShopId());
            in.setAdminId(userId);
            in.setInNums(saleReturn.getGoodsNumber());
            in.setSkuNumber(map.get("skuNumber").toString());
            inventoryDetailDao.inStorage(in);
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }


    //退货订单    财务审核  已完成退款
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response receivingReturnOrderAudit(String saleReturnNumber) {
        Response response = new Response();
        String userId = sessionUserUtil.getAdminAttr().getCustomerId();
        if (orderDao.updateSaleReturnStatus(userId, saleReturnNumber, 3) == 1) {
            //更改订单状态为交易成功
            SaleReturn saleReturn = orderDao.getSaleReturnBySaleReturnNumber(saleReturnNumber);

            //通过 goodsId ,orderNumber 获得子订单  更改 子订单 退货状态
            OrderSublist orderSublist = orderSublistMapper.getOrderSublistByGoodsIdAndOrderNumber(saleReturn.getOrderNumber(), saleReturn.getGoodsId());
            orderSublist.setIsSaleReturnSublist(3);
            orderSublistMapper.updateByPrimaryKeySelective(orderSublist);

            Order order = orderDao.getOrderInfoByOrderNumber22(saleReturn.getOrderNumber());
            if (order.getOrderStatus() == OrderStatus.SUCCESS.getStatus()) {//如果交易完成的申请退款，判断是否产生了返点，如果有从员工那扣除
                EmployeeIncome employeeIncome = orderDao.getEmployeeIncomeByOrderNumber(order.getOrderNumber());
                if (employeeIncome != null) {
                    Integer income1 = employeeIncome.getIncome();
                    Map<String, Object> map = systemDao.getCommissionRateByType(0);
//                int price = order.getRealPay() - saleReturn.getGoodsPrice();
                    //a 利率 h 退货订单利率后钱 c  当前收益钱 d 退货钱利率后
                    BigDecimal a = new BigDecimal(Integer.parseInt(map.get("commissionRate").toString())).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN);
                    BigDecimal d = new BigDecimal(saleReturn.getGoodsPrice()).multiply(a);
//                BigDecimal h = new BigDecimal(saleReturn.getGoodsPrice()).multiply(a);
                    BigDecimal c = new BigDecimal(income1).subtract(d);
                    int f = c.intValue();
                    int g = d.intValue();
//                Integer income = employeeIncome.getIncome();
                    //退货后订单收益
                    if (null != employeeIncome) {
                        Customer customer = customerDao.getCustomerById(employeeIncome.getCustomerId());
                        customer.setCashMoney(customer.getCashMoney() - g);
                        customerDao.updateByPrimaryKey(customer);
                        //员工提成记录
                        //修改员工提成记录
                        employeeIncome.setIncome(f);
                        employeeIncomeMapper.updateByPrimaryKey(employeeIncome);
//                    saveEmployeeIncome(customer.getCustomerId(), order.getOrderNumber(), employeeIncome.getIncome(), 0, employeeIncome.getOrderCustomerId());
                    }
                }

            } else if (order.getOrderStatus() != OrderStatus.SUCCESS.getStatus()) {//如果没有交易成功的订单，退货申请通过之后更改为交易成功
                orderDao.changeOrderStatus(order.getOrderNumber(), OrderStatus.SUCCESS.getStatus());
            }
            //如何使信誉值支付的，直接返给信誉值
            Map<String, Object> saleReturnMap = orderDao.getSaleReturnBySaleReturnNumberAndPayment(saleReturnNumber, 5);
            if (null != saleReturnMap) {
                int goodsNumber = Integer.parseInt(saleReturnMap.get("goodsNumber").toString());
                int goodsPrice = Integer.parseInt(saleReturnMap.get("goodsPrice").toString());
                String customerId = saleReturnMap.get("customerId").toString();
                Customer customer = customerDao.getCustomerById(customerId);
                if (customer.getCustomerCategoryId() == 2) {
                    Customer customer1 = new Customer();
                    customer1.setCustomerId(customerId);
                    customer1.setUseReputation(customer.getUseReputation() + (goodsNumber * goodsPrice));
                    customerDao.updateByPrimaryKey(customer1);
                    //保存信誉值记录
                    ReputationHistory reputation1 = new ReputationHistory();
                    reputation1.setCustomerId(customerId);
                    reputation1.setAmount(goodsNumber * goodsPrice);
                    reputation1.setType(1);
                    reputationHistoryDao.insert(reputation1);
                    response.setCode(RetCode.SUCCESS);
                } else {
                    response.setCode(RetCode.CUSTOMER_CATEGORY_ERROR);
                }
            } else {
                response.setCode(RetCode.SUCCESS);
            }
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    /**
     * 员工提成记录表
     *
     * @param customerId
     * @param orderNumber
     * @param income
     * @param type
     * @param orderCustomerId
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void saveEmployeeIncome(String customerId, //员工id
                                   String orderNumber,
                                   Integer income,
                                   int type,
                                   String orderCustomerId) {     //买家customerId
        EmployeeIncome employeeIncome = new EmployeeIncome();
        employeeIncome.setCustomerId(customerId);  //员工 id
        employeeIncome.setOrderNumber(orderNumber);
        employeeIncome.setIncome(income);
        employeeIncome.setType(type);
        employeeIncome.setOrderCustomerId(orderCustomerId);    //买家 customerId
        customerDao.saveEmployeeIncome(employeeIncome);
    }

    //订单生产中
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response orderGenerate(String orderNumber) {
        Response response = new Response();

        List<SaleReturn> saleReturn = saleReturnMapper.getSaleReturnByOrderNumber(orderNumber);

        for (SaleReturn saleReturn1 : saleReturn) {
            if (saleReturn1.getIsAudit() == 0 || saleReturn1.getIsAudit() == 1) {
                response.setCode(RetCode.NOT_DISPOSE_SALERETURN);
                return response;
            }
        }
        Order realOrder = orderDao.getOrderInfoByOrderNumber22(orderNumber);
        if (realOrder == null) {
            response.setCode(RetCode.ORDER_NULL);
            return response;
        }


        String adminId = sessionUserUtil.getAdminAttr().getAdminId();
        List<InventoryOut> outList = new ArrayList<>();
        //获取子订单中的基本信息
        List<Map<String, Object>> list = orderDao.getSublistByOrderNumber(orderNumber);
        int size01 = list.size();
        for (int j = 0; j < size01; j++) {
            Map<String, Object> skuNumber = goodsDao.getSkuNumberByGoodsId(list.get(j).get("goodsId").toString());
            String storageId = list.get(j).get("storageId").toString();
            String shopId = list.get(j).get("shopId").toString();
            String sku = skuNumber.get("skuNumber").toString();
            Integer goodsNumber = Integer.parseInt(list.get(j).get("goodsNumber").toString());
            //修改商品的销售数量
            goodsDao.updateGoodsSoldOutNumber(sku, goodsNumber);
            //减掉商品的库存
            Map<String, Object> inventoryMap = inventoryDao.getStorageGoodsNum(storageId, sku);
            if (null != inventoryMap) {
                //Integer goodsNum = Integer.parseInt(inventoryMap.get("goodsNumber").toString());
                //记录商品出库明细
                InventoryOut out = new InventoryOut();
                out.setStorageId(storageId);
                out.setShopId(shopId);
                out.setOrderId(orderNumber);
                out.setSkuNumber(sku);
                out.setType(0);
                out.setOutNums(goodsNumber);
                out.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
                out.setAdminId(adminId);
                outList.add(out);
                Inventory inventory = inventoryDao.selectByPrimaryKey((Long) (inventoryMap.get("inventoryId")));
                inventory.setGoodsNumber(inventory.getGoodsNumber() - goodsNumber);
                inventoryDao.updateByPrimaryKeySelective(inventory);
            } else {
                response.setCode(RetCode.STORAGE_GOODSNUMBERNULL);
                return response;
            }
        }
        //更改订单状态
        orderDao.changeOrderStatus(orderNumber, OrderStatus.IN_GENERATE.getStatus());
        //TODO
        try {
            Order order = orderDao.getOrderInfoByOrderNumber22(orderNumber);
            Customer customer = customerDao.getCustomerById(order.getCustomerId());
            log.info("订单生产中推送开始");
            PushUtil.sendAndroidAndIOS(customer.getCustomerMobile(), "customizedcast", "新消息", "您有一个订单已在生产中");
            log.info("订单生产中jieshu ");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("订单生产中推送失败：" + e.getMessage());
        }
        //批量保存出库明细
        if (!outList.isEmpty()) {
            orderDao.saveInventoryOutList(outList);
        }
        response.setCode(RetCode.SUCCESS);
        return response;
    }


    //更改换货订单的状态
    @Override
    public Response changeExchangeStatus(Exchange exchange) {
        Response response = new Response();
        String userId = sessionUserUtil.getAdminAttr().getAdminId();
        exchange.setAuditUserId(userId);
        if (1 == exchangeMapper.updateByPrimaryKeySelective(exchange)) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //获得用户全部的子订单
    @Override
    public Response orderSublistByCustomerId(Integer page, Integer size, Integer isAfterSale) {
        Response response = new Response();
        String customerId = sessionUserUtil.getUserAttr().getCustomerId();
        Integer start = (page - 1) * size;
        List<Map<String, Object>> map = orderDao.orderSublistByCustomerId(customerId, start, size, isAfterSale);

        int size01 = map.size();
        if (size01 > 0) {
            for (int i = 0; i < size01; i++) {
                try {
                    String receiving = map.get(i).get("receiving_time").toString().substring(0, map.get(i).get("receiving_time").toString().indexOf("."));
                    map.get(i).put("applicationStatus", judgeTime(receiving));
                } catch (ParseException e) {
                    e.printStackTrace();
                    log.info("判断订单是否还可退货：{}" + e.toString());
                    response.setCode(RetCode.REQUEST_ERROR);
                }
            }
            Integer totalNum = orderDao.orderSublistByCustomerIdAmount(customerId, isAfterSale);
            PageResult<Map<String, Object>> pageList = new PageResult<>(map, page, size, totalNum, "");

            response.setCode(RetCode.SUCCESS);
            response.put("pageList", pageList);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }


    @Override
    public Response orderSublistByCustomerIdForWeb(Integer page, Integer size, Integer isAfterSale, String keyword) {
        Response response = new Response();
        String customerId = sessionUserUtil.getUserAttr().getCustomerId();
        Integer start = (page - 1) * size;
        List<Map<String, Object>> map = orderMapper.orderSublistByCustomerIdForWeb(customerId, start, size, isAfterSale, keyword);

        int size01 = map.size();
        if (size01 > 0) {
            for (int i = 0; i < size01; i++) {
                try {
//                    map.get(i).put("applicationStatus", judgeTime(map.get(i).get("payTime").toString()));
                    String receiving = map.get(i).get("receiving_time").toString().substring(0, map.get(i).get("receiving_time").toString().indexOf("."));
                    map.get(i).put("applicationStatus", judgeTime(receiving));
                } catch (ParseException e) {
                    e.printStackTrace();
                    log.info("判断订单是否还可退货：{}" + e.toString());
                    response.setCode(RetCode.REQUEST_ERROR);
                }
            }
            Integer totalNum = map.size();
            PageResult<Map<String, Object>> pageList = new PageResult<>(map, page, size, totalNum, "");

            response.setCode(RetCode.SUCCESS);
            response.put("pageList", pageList);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }


    //点击售后申请跳转选择售后类型页面
    @Override
    public Response afterSaleTypeInfo(String orderSublistId) {
        Response response = new Response();
        Map<String, Object> map = orderDao.afterSaleTypeInfo(orderSublistId);
        if (null != map) {
            try {
                String receiving = map.get("receiving_time").toString().substring(0, map.get("receiving_time").toString().indexOf("."));
//                map.get(i).put("applicationStatus", judgeTime(receiving));
                map.put("applicationStatus", judgeTime(receiving));
                response.put("map", map);
                response.setCode(RetCode.SUCCESS);

            } catch (ParseException e) {
                e.printStackTrace();
                log.info("判断订单是否还可退货：{}" + e.toString());
                response.setCode(RetCode.REQUEST_ERROR);
            }
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //确认发货
    @Override
    public Response confirmDelivery(String orderNumber, String logisticsCompany, String trackingNumber) {
        Response response = new Response();

        List<SaleReturn> saleReturn = saleReturnMapper.getSaleReturnByOrderNumber(orderNumber);

        for (SaleReturn saleReturn1 : saleReturn) {
            if (saleReturn1.getIsAudit() == 0 || saleReturn1.getIsAudit() == 1) {
                response.setCode(RetCode.NOT_DISPOSE_SALERETURN);
                return response;
            }
        }

        //更改订单状态并填写物流信息
        orderDao.confirmDelivery(orderNumber, logisticsCompany, trackingNumber);
        //TODO
        try {
            Order order = orderDao.getOrderInfoByOrderNumber22(orderNumber);
            Customer customer = customerDao.getCustomerById(order.getCustomerId());
            log.info("确认发货推送开始");
            PushUtil.sendAndroidAndIOS(customer.getCustomerMobile(), "customizedcast", "新消息", "您有一个订单已发货");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("您有一个订单已发货推送失败：" + e.getMessage());
        }
        response.setCode(RetCode.SUCCESS);
        return response;
    }


    //后端查询所有的退换货
    @Override
    public Response getSaleReturnList(Integer isAudit, Integer type, Integer page, Integer size, String draw,
                                      String search, String shopId, String startTime, String endTime) {
        Response response = new Response();
        Integer start = (page - 1) * size;

        List<Map<String, Object>> saleReturnMap;
        int saleReturnAmount;
        //type!=null查询退货订单，反之查询换货订单
        if (null != type) {
            saleReturnMap = orderDao.getSaleReturnList(isAudit, start, size, search, shopId, startTime, endTime);
            saleReturnAmount = orderDao.getSaleReturnAmount(isAudit, search, shopId, startTime, endTime);
        } else {
            saleReturnMap = orderDao.getExchangeList(isAudit, start, size, search, shopId, startTime, endTime);
            saleReturnAmount = orderDao.getExchangeListAmount(isAudit, search, shopId, startTime, endTime);
        }
        PageResult<Map<String, Object>> pageList = new PageResult<>(saleReturnMap, page, size, saleReturnAmount, draw);
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }


    @Override
    public Response saleReturnAudit(Integer isAudit, Integer saleReturnStatus, Integer page, Integer size, String draw,
                                    String search, String shopId, String startTime, String endTime) {
        Response response = new Response();
        Integer start = (page - 1) * size;

        List<Map<String, Object>> saleReturnMap;
        int saleReturnAmount;
        saleReturnMap = saleReturnMapper.getSaleReturnList22(isAudit, saleReturnStatus, start, size, search, shopId, startTime, endTime);
        saleReturnAmount = saleReturnMapper.getSaleReturnAmount22(isAudit, saleReturnStatus, search, shopId, startTime, endTime);
        PageResult<Map<String, Object>> pageList = new PageResult<>(saleReturnMap, page, size, saleReturnAmount, draw);
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }


    //换货 客户确认收货接口
    @Override
    public Response exchangeReturnOrder(String exchangeId) {
        Response response = new Response();
        Exchange exchange = exchangeMapper.selectByPrimaryKey(exchangeId);
        exchange.setExchangeStatus(3);
        if (exchangeMapper.updateByPrimaryKeySelective(exchange) == 1) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }


    //定时任务--更改订单为交易成功
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void disposeOrder() throws Exception {
        //查看仓库发货之后超过多少天（7天）之后，客户如果没有确认收货，自动进行状态更改
        //应该用发货的时间+7天的时间如果《现在的时间，满足修改订单状态的条件
        List<Map<String, Object>> orderMap = orderDao.getOrderListByOrderStatus(OrderStatus.DELIVERED.getStatus());
        int size01 = orderMap.size();
        for (int i = 0; i < size01; i++) {
            //指定的退换货时间段  默认 七天
            final String afterSaleApplicationTime = PropUtils.getString("automaticReceivingTime");
            String deliveryTime = orderMap.get(i).get("deliveryTime").toString();
            // 支付时间
            long time = format.parse(deliveryTime).getTime();
            if ((Integer.parseInt(afterSaleApplicationTime) + time) < System.currentTimeMillis()) {
                //更改订单状态为交易成功
                orderDao.updateOrderStatus(orderMap.get(i).get("orderNumber").toString(), OrderStatus.SUCCESS.getStatus());
                profitSharing(orderMap.get(i).get("orderNumber").toString());
            }
        }
    }

    //定时任务--修改用户可提现金额
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void disposeMoney() throws Exception {
        //查看收益表数据,将超过7天的订单改为不可退货状态
        //应该用获取收益的时间+7天的时间如果《现在的时间，满足修改订单状态的条件
        List<Map<String, Object>> cashMoney = employeeIncomeMapper.getCanCashMoney();
        for (int i = 0; i < cashMoney.size(); i++) {
            String customer_id = (String) cashMoney.get(i).get("customerId");
            int hcashMoney1 = Integer.parseInt(String.valueOf(cashMoney.get(i).get("hcashMoney")));
            Customer customer = customerDao.getCustomerById(customer_id);
            int hcashMoney2 = customer.getHcashMoney();
            int hcashMoney = hcashMoney1 + hcashMoney2;
            if (1 != customerDao.updateByHaveCashMoney(hcashMoney, customer_id)) {
            }
        }
        employeeIncomeMapper.updateStatus();
    }


    //处理未支付的订单
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void disposeUnpaidOrder() {
        List<Map<String, Object>> orderMap = orderDao.getOrderListByOrderStatus(OrderStatus.UNPAID.getStatus());
        int size01 = orderMap.size();
        for (int i = 0; i < size01; i++) {
            //指定的退换货时间段  默认 七天
            final String unpaidOrderTime = PropUtils.getString("unpaidOrderTime");
            String createTime = orderMap.get(i).get("createTime").toString();
            // 支付时间
            long time = 0;
            try {
                time = format.parse(createTime).getTime();
            } catch (ParseException e) {
                log.debug("get createTime error : {}" + e.toString());
            }
            if ((Integer.parseInt(unpaidOrderTime) + time) < System.currentTimeMillis()) {
                //删除此订单
                orderDao.deleteByPrimaryKey(orderMap.get(i).get("orderId").toString());
                //删除子订单
                orderDao.deleteSublistByOrderNumber(orderMap.get(i).get("orderId").toString());
            }
        }
    }

    //处理未支付的需求订单
    @Override
    public void disposeUnpaidDemand() {
        List<Map<String, Object>> demandMap = demandDao.getDemandByDemandStatus(DemandStatus.PROCESSING.getStatus());
        int size01 = demandMap.size();
        for (int i = 0; i < size01; i++) {
            //指定的退换货时间段  默认 三天
            final String unpaidOrderTime = PropUtils.getString("unpaidDemandTime");
            String serviceTime = demandMap.get(i).get("serviceTime").toString();
            // 支付时间
            long time = 0;
            try {
                time = format.parse(serviceTime).getTime();
            } catch (ParseException e) {
                log.debug("get serviceTime error : {}" + e.toString());
            }
            if ((Integer.parseInt(unpaidOrderTime) + time) < System.currentTimeMillis()) {
                //修改此需求订单为交易失败
                demandDao.updateStatus(demandMap.get(i).get("demandId").toString(), DemandStatus.FAILURE.getStatus());
            }
        }
    }

    @Override
    public Response addNotesByOrderId(String orderId, String notes) {
        Response response = new Response();

        Order order = new Order();
        order.setOrderId(orderId);
        order.setNotes(notes);
        Integer num = orderMapper.updateByPrimaryKeySelective(order);
        if (num == 1) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    @Override
    public Response getStatus(String orderNumber, String goodsId) {
        Response response = new Response();
        List<SaleReturn> saleReturnList = saleReturnMapper.verSole(orderNumber, goodsId);
        List<Exchange> exchangeList = exchangeMapper.verSole(orderNumber, goodsId);
        //如果是退货订单
        if (saleReturnList.size() > 0) {
            response.put("saleReturnStatus", saleReturnList.get(0).getSaleReturnStatus());
            response.put("isAudit", saleReturnList.get(0).getIsAudit());
            response.put("exchangeStatus", -1);//退换中  不能换货
        } else if (exchangeList.size() > 0) {
            response.put("saleReturnStatus", -1);//换货中  不能退货
            response.put("exchangeStatus", exchangeList.get(0).getExchangeStatus());
            response.put("isAudit", exchangeList.get(0).getIsAudit());
        } else {
            response.put("saleReturnStatus", -2);//可以换货
            response.put("exchangeStatus", -2);//可以退换
        }

        response.setCode(RetCode.SUCCESS);
        return response;
    }


    /**
     * 判断订单是否还可以申请退货
     *
     * @param orderTime
     * @return
     * @throws ParseException
     */
    private int judgeTime(String orderTime) throws ParseException {
        //指定的退换货时间段  默认 七天
        final String afterSaleApplicationTime = PropUtils.getString("afterSaleApplicationTime");
        // 收货时间
        long time = format.parse(orderTime).getTime();
        if ((Integer.parseInt(afterSaleApplicationTime) + time) < System.currentTimeMillis()) {
            return -1;
        } else {
            return 1;
        }
    }


}
